<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator函数的基本用法</title>
</head>
<body>
    <h1>Generator函数的基本用法</h1>

    <script>
        // yield表达式
        function* dataConsumer() {
            console.log('开始...');
            console.log(`1. ${yield}`);
            console.log(`2. ${yield}`);
            return '结束';
        }

        let dc = dataConsumer();
        dc.next(); // 开始...
        dc.next('a'); // 1. a
        dc.next('b'); // 2. b

        // Generator函数的遍历
        function* fibonacci() {
            let [prev, curr] = [0, 1];
            while (true) {
                yield curr;
                [prev, curr] = [curr, prev + curr];
            }
        }

        const fib = fibonacci();
        for (let i = 0; i < 10; i++) {
            console.log(fib.next().value);
        }

        // Generator函数的返回值
        function* numbers() {
            yield 1;
            yield 2;
            return 3;
        }

        const nums = numbers();
        for (let n of numbers()) {
            console.log(n); // 只输出1, 2，不包括return的3
        }

        // yield*表达式
        function* bar() {
            yield 'x';
            yield* foo();
            yield 'y';
        }

        function* foo() {
            yield 'a';
            yield 'b';
        }

        for (let v of bar()) {
            console.log(v); // x, a, b, y
        }
    </script>
</body>
</html> 